//
//  USAuthViewController.m
//  USEvent
//
//  Created by fengzifeng on 15/9/15.
//  Copyright (c) 2015年 fengzifeng. All rights reserved.
//

#import "MKZUSAuthViewController.h"
#import "MKZFFLoginCell.h"
//#import "DrBaseWebViewController.h"
//#import "FFPlateDetailViewController.h"

@interface MKZUSAuthViewController ()
@property (nonatomic, strong) UILabel * Label;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) MKZFFLoginUser *loginObj;
@property (nonatomic, strong) UIButton *logButton;


@end

@implementation MKZUSAuthViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupUI];
//    self.view.backgroundColor = [UIColor yellowColor];
//    self.navigationBar.hidden = YES;
    
    self.type = loginType;
    if (_type == loginType) {
        _titleArray = @[@"手机号",@"密码"];
    } else if (_type == reginType){
        _titleArray = @[@"手机号",@"密码"];
    } else {
        _titleArray = @[@"邮箱"];
    }
    
    _tableView.tableHeaderView = [self getHeadView];
    _tableView.tableFooterView = [self getFootView];
    _loginObj = [[MKZFFLoginUser alloc] init];
    __weak typeof(self) weakSelf = self;
//    [self.view setTapActionWithBlock:^{
//        [weakSelf.view endEditing:YES];
//    }];

}
-(void)setupUI{
    
    UIImageView * bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    bgImageView.backgroundColor = [UIColor colorWithHexString:Background_Color];
    bgImageView.userInteractionEnabled = YES;
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.mas_equalTo(self.view).offset(0);
//        make.height.mas_equalTo(80);
    }];
    [self.view insertSubview:bgImageView atIndex:0];
    _tableView.backgroundColor = [UIColor clearColor];
    
    
    UIImageView * topImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    topImageView.backgroundColor = [UIColor colorWithHexString:Navigation_And_StatusBar_Color];
    topImageView.userInteractionEnabled = YES;
    [self.view addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view).offset(0);
        make.height.mas_equalTo(80);
    }];
    
    UILabel * Label = [UILabel new];
    Label.text = @"登录";
    Label.textColor = [UIColor whiteColor];
    Label.font = [UIFont systemFontOfSize:22 weight:UIFontWeightBold];
    [topImageView addSubview:Label];
    [Label mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(topImageView.mas_top).offset(30);
        make.centerY.mas_equalTo(topImageView.mas_centerY).offset(30);
        make.centerX.mas_equalTo(topImageView.mas_centerX).offset(0);
        make.height.mas_equalTo(30);
    }];
    self.Label = Label;
    
    UIButton *qianbaoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [qianbaoButton setImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [topImageView addSubview:qianbaoButton];
    [qianbaoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(topImageView.mas_left).offset(0);
        make.centerY.mas_equalTo(Label.mas_centerY).offset(0);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(40);
    }];
    [qianbaoButton bk_whenTapped:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (UIView *)getHeadView
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 148)/2.0, 42, 80, 80)];
    iconImageView.image = [UIImage imageNamed:@"mylogo"];
    [headView addSubview:iconImageView];
    iconImageView.layer.masksToBounds = YES;
    iconImageView.layer.cornerRadius = 25;
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(headView.mas_top).offset(30);
        make.centerX.mas_equalTo(headView.mas_centerX).offset(0);
        make.height.mas_equalTo(120);
        make.width.mas_equalTo(120);
        
//        make.bottom.mas_equalTo(headView.mas_bottom).offset(-50);
//        make.left.mas_equalTo(headView.mas_left).offset(20);
//        make.height.mas_equalTo(50);
//        make.width.mas_equalTo(50);
    }];
    
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
    UILabel * Label = [UILabel new];
    Label.textAlignment = NSTextAlignmentLeft;
    Label.text = [NSString stringWithFormat:@"欢迎登录%@",app_Name];
    Label.textColor = [UIColor blackColor];
    Label.font = [UIFont boldSystemFontOfSize:17];
    [headView addSubview:Label];
    [Label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(iconImageView.mas_bottom).offset(30);
        make.centerX.mas_equalTo(headView.mas_centerX).offset(0);
        make.height.mas_equalTo(21);
//        make.width.mas_equalTo(50);
    }];
    
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 30, 30)];
    UIImage *image = [UIImage imageNamed:@"login_close"];
//    [closeButton setImage:[image imageScaledToSize:CGSizeMake(20, 20)]  forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickClose) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:closeButton];
    
    
    return headView;
}

- (UIView *)getFootView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-60, 130)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    [button setBackgroundImage:[UIImage imageWithColor:[UIColor redColor]] forState:UIControlStateNormal];
    button.backgroundColor =[UIColor whiteColor];
    button.frame = CGRectMake(19, 22, 250, 42);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 21;
    button.center = CGPointMake(view.center.x, button.center.y);
    [button addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    UIButton *downButton = [UIButton buttonWithType:UIButtonTypeCustom];
    downButton.frame = CGRectMake(19, CGRectGetMaxY(button.frame) + 20, 250, 42);
    downButton.layer.masksToBounds = YES;
    downButton.layer.cornerRadius = 21;
    downButton.center = CGPointMake(view.center.x, downButton.center.y);
    downButton.backgroundColor =[UIColor whiteColor];
    [downButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    downButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [downButton addTarget:self action:@selector(clickSwitch) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:downButton];
    self.downButton = downButton;
    _logButton = button;
    if (_type == loginType) {
        [button setTitle:@"登录" forState:UIControlStateNormal];
        self.Label.text = @"登录";
        [downButton setTitle:@"没有账号？立即注册" forState:UIControlStateNormal];

    } else if (_type == reginType) {
        [button setTitle:@"注册" forState:UIControlStateNormal];
        self.Label.text = @"注册";
        [downButton setTitle:@"已有账号？立即登录" forState:UIControlStateNormal];
    } else {
        [button setTitle:@"发送至验证邮箱" forState:UIControlStateNormal];
        [downButton setTitle:@"已有账号？立即登录" forState:UIControlStateNormal];
    }

    return view;
}

- (IBAction)didClickAgreeProtocol:(UIButton *)sender
{
    protocolImageView.hidden = !protocolImageView.hidden;
    _logButton.enabled = !protocolImageView.hidden;
}

- (IBAction)clicktongyi:(id)sender {
    ZKWKWebViewController *vc = [ZKWKWebViewController new];
    vc.url =  [NSString stringWithFormat:@"%@%@",@"http://39.107.109.205:8081",@"/yrj/frame/h5/privacypolicy"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)clickSwitch
{
    if (_type == loginType) {
        if ([self.downButton.titleLabel.text isEqualToString:@"忘记密码"]) {
            _type = getPassword;
        } else {
            _type = reginType;

        }
    } else if (_type == reginType) {
        _type = loginType;
    } else {
        _type = loginType;
    }
    
    if (_type == loginType) {
        _titleArray = @[@"手机号",@"密码"];
    } else if (_type == reginType){
        _titleArray = @[@"手机号",@"密码",];
    } else {
        _titleArray = @[@"邮箱"];
    }
    _loginObj = [[MKZFFLoginUser alloc] init];

    _tableView.tableHeaderView = [self getHeadView];
    _tableView.tableFooterView = [self getFootView];
    [_tableView reloadData];
//    [self dismissViewControllerAnimated:NO completion:nil];
//    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_LoginRegSwitch object:@(!_isLogin)];


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"MKZFFLoginCell";
    MKZFFLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.contentView.backgroundColor = [UIColor clearColor];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil] firstObject];
        cell.loginObj = _loginObj;
        cell.type = _type;
    }
    
    [cell updateCell:_titleArray[indexPath.row]];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)clickClose
{
    [self.view endEditing:YES];

//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];

}

-(BOOL)isRegist{
    BOOL isFlag = NO;
    NSArray *registUser = [[MKZHDDataManager shareManager]  getAllRegistUser];
    for (NSDictionary *dict in registUser) {
        if ([dict[@"phone"] isEqualToString:_loginObj.username] && [dict[@"psw"] isEqualToString:_loginObj.password]) {
            return YES;
        }
    }
    return isFlag;
}


- (void)login
{
    
    
    if([_loginObj.username length] == 0){
        [SUIUtils makeShortToastAtCenter:@"请输入手机号"];
        return;
    }
    if([_loginObj.password length] == 0){
        [SUIUtils makeShortToastAtCenter:@"请输入密码"];
        return;
    }
    if([_loginObj.username length] != 11){
        [SUIUtils makeShortToastAtCenter:@"您输入的手机号有误，请重新输入"];
        return;
    }
    
    NSArray *deleteids = [userDefault objectForKey:@"deleteid"];
    if (deleteids) {
        if ([deleteids containsObject:_loginObj.username]) {
            return   [SUIUtils makeShortToastAtCenter:@"您的账号已经注销，无法登录"];;
        }
    }
  
    if (_type == loginType) {
        [SVProgressHUD show];
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            if ([self isRegist]) {
                [self.navigationController popViewControllerAnimated:YES];
                [SUIUtils makeShortToastAtCenter:@"登录成功"];
                [userDefault setObject:_loginObj.username forKey:@"USERPHONE"];
                [userDefault setObject:_loginObj.password forKey:@"USERPASSWORD"];
                [userDefault synchronize];
            }else{
                [SUIUtils makeShortToastAtCenter:@"账号或者密码错误，请重新输入"];
            }
        });

        
    
    } if (_type == reginType) {
        [SVProgressHUD show];
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            
            [[MKZHDDataManager shareManager] registUserWithData:@{@"phone":_loginObj.username,@"psw":_loginObj.password}];
            [SUIUtils makeShortToastAtCenter:@"注册成功"];
        });
    }

//    [[DrHttpManager defaultManager] getRequestToUrl:requestUrl params:nil complete:^(BOOL successed, HttpResponse *response) {
//        if (successed) {
//            ZHUFFLoginUser *user = [ZHUFFLoginUser objectWithKeyValues:response.payload[@"data"]];
//            NSString *str = response.payload[@"data"][@"message"];
//            if (str.length) [USSuspensionView showWithMessage:str];
//
//            if ([user.status integerValue] == 1) {
//
//                if (_type != loginType) {
//                    if (_type == getPassword) {
//                        [USSuspensionView showWithMessage:@"发送成功"];
//                    }
//                    [self clickSwitch];
//                } else {
//                    [AuthData loginSuccess:@{@"uid":user.uid,@"username":user.username,@"signCode":user.signCode}];
//                    [self.navigationController popToRootViewControllerAnimated:YES];
////                    [self dismissViewControllerAnimated:YES completion:nil];
//                }
//            } else {
//                if (!str.length) {
//                    if (_type == loginType) {
//                        [USSuspensionView showWithMessage:@"账号密码不匹配"];
//                    } else if (_type == getPassword) {
//                        [USSuspensionView showWithMessage:@"邮箱有误，请重试"];
//                    }
//                }
////                if (_type == loginType && !str.length) [USSuspensionView showWithMessage:@"账号密码不匹配"];
////                if (_type == loginType && !str.length) [USSuspensionView showWithMessage:@"账号密码不匹配"];
//
////                NSString *str = response.payload[@"data"][@"message"];
////                if (str.length) [USSuspensionView showWithMessage:str];
//            }
//        } else {
//            if (_type == loginType) {
//                [USSuspensionView showWithMessage:@"账号密码不匹配"];
//            } else if (_type == getPassword) {
//                [USSuspensionView showWithMessage:@"邮箱有误，请重试"];
//            }
//        }
//    }];
//
//
//    if (_isLogin) {
//
//    } else {
//    }
//    [AuthData loginSuccess:@{@"uid":@"1",@"nickname":@"深刻觉得脚九分裤"}];
    

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
